package org.linlinjava.litemall.admin.util;

import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.ThreadContext;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.util.MerchantPermission;
import org.linlinjava.litemall.db.util.MerchantPermissionConstant;

import org.apache.shiro.subject.Subject;
import java.util.Map;

public class MerchantPermissionDialect extends MybatisPermissionDialect {
    private final Log log = LogFactory.getLog(MerchantPermissionDialect.class);

    // 全表加过滤
    @Override
    public String permissionSql(MappedStatement ms, String sql) {
        StringBuilder sbSql = new StringBuilder(sql);

        Subject subject = SecurityUtils.getSubject();
        log.info(subject);
        Object principal = subject.getPrincipal();
        String merchantId = "";
        log.info("principal");
        log.info(principal);

        // 后端用户登录
        LitemallAdmin userAdmin = null;

        if(principal instanceof LitemallAdmin) {
            log.info("principal is admin");
            userAdmin = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
            if (userAdmin != null) {
                //获取当前登录人所属商户标识
                merchantId = String.valueOf( userAdmin.getMerchantId() );
            }
        }

        // 前端用户登录
        LitemallUser user = null;

        if(principal instanceof LitemallUser) {
            log.info("principal is user");
            user = (LitemallUser) SecurityUtils.getSubject().getPrincipal();
            if (user != null) {
                //获取当前登录人所属商户标识
                merchantId = String.valueOf( user.getMerchantId() );
            }
        }

        //如果有动态参数 merchantId
        String mchtid =(String) subject.getSession().getAttribute("X-Litemall-mchtid");
        log.info("X-Litemall-mchtid");
        log.info(mchtid);
        if(StringUtils.isBlank(merchantId) && StringUtils.isNotBlank(mchtid)){
            log.info("X-Litemall-mchtid");
            merchantId = mchtid;
        }


        if(StringUtils.isNotBlank(merchantId)){
            sbSql = new StringBuilder("select * from (")
                    .append(sbSql)
                    .append(" ) s ")
                    .append(" where s.merchant_id = "+ merchantId +" ");
        }

        log.info("权限拼装SQL：" + sbSql.toString());

        return sbSql.toString();
    }

    // 按注解加过滤
    // @Override
    public String permissionSqlAnnotation(MappedStatement ms, String sql) {


        StringBuilder sbSql = new StringBuilder(sql);

        // 商户数据权限拦截 begin
        //获取需要进行拦截的DAO层namespace拼接串
        // String interceptNamespace = PermissionConfig.getConfig("permission.intercept.namespace");
        String interceptNamespace = "org.linlinjava.litemall.db.dao.LitemallAdMapper";

        log.info("interceptNamespace " + interceptNamespace);

        //获取当前mapped的namespace

        String className =  ms.getId().substring(0,  ms.getId().lastIndexOf("."));

        if(StringUtils.isNotBlank(interceptNamespace)){
            //判断配置文件中的namespace是否与当前的mapped namespace匹配，如果包含则进行拦截，否则放行
            log.info("className " + className);
            if(interceptNamespace.contains(className)){
                //获取数据权限注解对象
                MerchantPermission merchantPermission = MerchantPermissionUtils.getPermissionByDelegate(ms);
                log.info(merchantPermission);
                if (merchantPermission != null){
                    //获取注解的值
                    String permissionAopValue = merchantPermission.value();
                    //判断注解是否开启拦截
                    if(MerchantPermissionConstant.MERCHANT_PERMISSION_INTERCEPT.equals(permissionAopValue) ){
                        if(log.isInfoEnabled()){
                            log.info("数据权限拦截【拼接SQL】...");
                        }
                        //返回拦截包装后的sql
                        //sql = permissionSql(sql);
                        //获取当前登录人
                        // User user = UserUtils.getLoginUser();
                        LitemallAdmin user = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();

                        String merchantId = "";
                        if (user != null) {
                            //获取当前登录人所属商户标识
                            merchantId = String.valueOf( user.getMerchantId() );
                        }
                        //如果有动态参数 merchantId

                        if(StringUtils.isNotBlank(merchantId)){
                            sbSql = new StringBuilder("select * from (")
                                    .append(sbSql)
                                    .append(" ) s ")
                                    .append(" where s.merchant_id = "+ merchantId +" ");
                        }
                    } else {
                        if(log.isInfoEnabled()){
                            log.info("数据权限放行...");
                        }
                    }
                }

            }
        }
        //商户数据权限拦截 end

        log.info("权限拼装SQL：" + sbSql.toString());

        return sbSql.toString();

    }

    @Override
    public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
        return null;
    }
}
